﻿from t2mysql import models
from t2mysql.models import *
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.http import JsonResponse
import json
import sys
sys.path.append('../')


# Create your views here.
def index(request):
    '''首页

    准备工作
    '''
    markdown = """

链接示例 | 说明
---|---
[initialize](/10/888) | 生成初始数据
[users](/10/users) | 获取用户列表
[del](/10/del?uid=10) | 删除用户
[edit](/10/edit?uid=11&username=AAA) | 修改用户

"""
    context = {
        'title': 'Home',
        'markdown': markdown,
    }
    return render(request, 'marked.html', context)


def initialize(request):
    """创建原始数据
    """
    models.build_user()   # 生成初始数据
    return HttpResponse('创建数据成功!')


def get_dt(request):
    """查询所有用户
    """
    getusers = Users.objects.all().values()
    data = {}
    data['users'] = list(getusers)
    return JsonResponse(data)


def del_dt(request):
    """删除数据
    """
    try:
        uid = request.GET['uid']
        ob = Users.objects.get(id=uid).delete()
        return HttpResponse('删除成功!')
    except:
        return HttpResponse('没有找到要修改的信息!')


def edit_dt(request):
    """修改数据
    """
    try:
        uid = request.GET['uid']
        ob = Users.objects.get(id=uid)
        ob.username = request.GET['username']
        ob.save()
        return HttpResponse('修改成功!')
    except:
        return HttpResponse('没有找到要修改的信息!')
